package com.dinzeer.sjapadder.se;

import com.dinzeer.legendreliclib.lib.util.slashblade.SlashBladeUtil;
import com.dinzeer.sjapadder.register.SjaStacksReg;
import mods.flammpfeil.slashblade.capability.slashblade.ISlashBladeState;
import mods.flammpfeil.slashblade.event.SlashBladeEvent;
import mods.flammpfeil.slashblade.item.ItemSlashBlade;
import mods.flammpfeil.slashblade.registry.SpecialEffectsRegistry;
import mods.flammpfeil.slashblade.registry.specialeffects.SpecialEffect;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.event.entity.living.LivingDamageEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

import java.util.List;

@Mod.EventBusSubscriber
public class ClearMind extends SpecialEffect {


    public ClearMind() {
        super(30);
    }




    public static Boolean HasSe(LivingEntity entity){
        if (!(entity.getMainHandItem().getCapability(ItemSlashBlade.BLADESTATE).isPresent()))return false;
        ISlashBladeState state= SlashBladeUtil.getState(entity.getMainHandItem());
        List<ResourceLocation> effects = state.getSpecialEffects();
        for (ResourceLocation effectId : effects) {
            SpecialEffect effect = SpecialEffectsRegistry.REGISTRY.get().getValue(effectId);
            if (effect instanceof ClearMind Effect&&entity instanceof Player player) {

                return state.hasSpecialEffect(effectId);


            }
        }
        return false;
    }
    @SubscribeEvent
    public static void onLivingUpdate(SlashBladeEvent.UpdateEvent event){
        if (event.getEntity() instanceof Player player){
            if (HasSe(player)){
                if (SjaStacksReg.ClearMindCD.getCurrentStacks(player)>0){
                    SjaStacksReg.ClearMindCD.addStacks(player, -1);
                }
            }
        }
    }


    @SubscribeEvent
    public static void onLivingDamage(LivingDamageEvent event) {
        LivingEntity entity = event.getEntity();
        if (entity instanceof Player player && HasSe(player)) {
            // 检查是否为致命伤害
            float damageAmount = event.getAmount();
            float currentHealth = player.getHealth();

            if (damageAmount >= currentHealth
                    && SjaStacksReg.ClearMindCD.getCurrentStacks( player)<=0) {
                // 取消伤害事件
                event.setCanceled(true);

                // 恢复玩家状态
                player.setHealth(player.getMaxHealth());
                player.getFoodData().setFoodLevel(20);
                player.getFoodData().setSaturation(20.0F);
                player.removeAllEffects();
                player.clearFire();
                SjaStacksReg.ClearMindCD.addStacks( player, SjaStacksReg.ClearMindCD.getMaxStacks());
            }
        }
    }


}
